package com.zxct.wyserver.http;

import com.socks.library.KLog;
import com.zxct.wyserver.MyApp;
import com.zxct.wyserver.util.SPUtils;
import com.zxct.wyserver.util.SignatureUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by lanyu on 2018/1/29.
 */

public class NetworkInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();

        String apptimestamp = String.valueOf(System.currentTimeMillis());
        SPUtils sp = new SPUtils(MyApp.getContext(), "userID");
        String appkey = sp.getString("APPKEY");
        String appsecret = sp.getString("APPSECRET");

        Request request = null;
        List<Map<String, String>> mapList = handleUrl(original);
        Map<String, String> map = mapList.get(0);
        Map<String, String> oldmap = mapList.get(1);
        //KLog.d(map);
        map.put("appid", Apn.APPID);
        map.put("appkey", appkey);
        map.put("apptimestamp", apptimestamp);

        SignatureUtils.urlMap(map, appsecret);

        String appsign = map.get("appsign");
        //KLog.d(appsign);

        final String newUrl = oldmap.get("urlHead") + "appid=" + Apn.APPID + "&appkey=" + appkey + "&" + oldmap.get("url") +
                "&apptimestamp=" + apptimestamp + "&appsign=" + map.get("appsign");

        KLog.d("newUrl**********" + newUrl);
        //重定向url
        if (original.method() == "GET") {
            request = new Request.Builder().url(newUrl).build();
        } else {
            request = new Request.Builder().post(original.body()).url(newUrl).build();
        }

        KLog.d(request);

        return chain.proceed(request);
    }

    private List<Map<String, String>> handleUrl(Request original) {
        //KLog.d(original.url());
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        String oldUrl = original.url().toString();
        String url = "a=a";
        String urlHead = oldUrl;
        if (oldUrl.lastIndexOf("?") > 0) {
            url = oldUrl.substring(oldUrl.lastIndexOf("?")).replace("?", "");
            urlHead = oldUrl.substring(0, oldUrl.lastIndexOf("?"));
            //KLog.d(url);
            String[] params = url.split("&");

            for (String param : params) {
                String[] keyValue = param.split("=");
                if (keyValue.length > 1) {
                    map.put(keyValue[0], keyValue[1]);
                }
            }
        }
        list.add(map);
        Map<String, String> urlmap = new HashMap<>();
        urlmap.put("url", url);
        urlmap.put("urlHead", urlHead + "?");
        list.add(urlmap);
        return list;
    }
}

